<!--
 @description 客户-商机记录
 @fileName OptyRecord.vue
 @author zengqiongying
 @created 2022/11/11 13:13:38
-->
<template>
  <div class="opty-record">
    <List
      ref="list"
      class="c-list-scroll"
      :finished.sync="finished"
      :reset-fun="resetData"
      :load="load"
      :refresh="load"
      :default-active="true"
    >
      <div v-for="(item,i) in list" :key="i" class="record-item" @click="handleDetail(item)">
        <div class="item-title">
          <span class="c-blak fw">商机编码：{{ item.code }}</span>
          <!-- <span class="tip">{{ getNoFollowDateCount(item) }}天未跟进</span> -->
        </div>
        <div class="c-blak">跟进人：<span class="fw">{{ getFollowupUser(item.optyFollowUpUsers) }}</span></div>
        <div class="item-content">
          <div>最新跟进记录：</div>
          <div v-html="getHtmlContent(item.lastFollowupContent)" />
          <div>{{ item.lastFollowupTime | filterTime }}</div>
        </div>
        <div class="item-bottom">
          <!-- <div class="btn" @click.stop="handleFollowCustomer(item)">跟进</div> -->
          <!-- <div class="btn" @click.stop="handleToPage('/customer/followUp/opty',item)">跟进</div> -->
          <div v-if="ableAllocationDesigner" class="btn" @click.stop="handleToPage('/customer/opty/allocation',item)">分配设计师</div>
          <div class="btn" @click.stop="handleToPage('/customer/opty/addCate',item)">添加品类</div>
        </div>
      </div>
    </List>
  </div>
</template>

<script>
import List from '@/components/List'
import mixin from './mixin'
import { bus } from '@/utils/bus'
import { optyDisPage } from '@/apis/customer'
// import { getOptyDetail } from '@/apis/optyCategory'
export default {
  name: 'CustomerOptyRecord',
  components: { List },
  mixins: [mixin],
  data() {
    return {
      list: [],
      finished: false // 列表是否加载完成
    }
  },
  computed: {
    filtersRaw() {
      return [
        { id: 'clueCustomerId', property: 'clueCustomerId', value: this.clueCustomerId, operator: '=' }
      ]
    },
    ableAllocationDesigner() {
      // 店长 top_shop_mg、设计主管 top_design_mg，才允许分配设计师
      const t = this.$store.getters.userInfo
      const positionCodes = t.positionCodes || []
      return positionCodes.some(v => ['top_shop_mg', 'top_design_mg'].includes(v))
    }
  },
  created() {
    window.refreshOptyItem = ({ type, id }) => {
      this.refreshOptyItem({ type, id })
    }
    bus.$on('refreshOptyItem', ({ type, id }) => {
      this.refreshOptyItem({ type, id })
    })
  },
  methods: {
    initData() {
      this.resetPageData()
    },
    resetPageData() {
      if (this.$refs.list) {
        this.$refs.list.resetPageData()
      }
    },
    load(page, rows) {
      const data = new FormData()
      data.append('page', page)
      data.append('rows', rows)
      data.append('sort', 'createTime')
      data.append('order', 'desc')
      data.append('filtersRaw', JSON.stringify(this.filtersRaw))
      data.append('paramsRaw', JSON.stringify({ queryDesignerList: '1' }))

      const headers = {
        'Permission-PerCode': this.isCommonCustomerPool ? 'common_customer_pool' : 'my_customer_pool',
        'Permission-App': 'top2-crm-app'
      }
      return optyDisPage(data, headers).then(res => {
        const records = res.data.records || []
        if (page === 1) {
          this.$refs.list ? this.$refs.list.page = 1 : ''
          this.list = records
        } else {
          this.list.push(...records)
        }
        if (this.list.length >= res.data.total) {
          this.finished = true
        }
      })
    },
    resetData() {
      this.list = []
    },
    handleToPage(path, data) {
      const { id } = data
      const query = { id }
      this.$router.push({
        path,
        query
      })
    },
    handleFollowCustomer(data) {
      const id = data.clueCustomerId
      const query = { id }
      this.$router.push({
        path: '/customer/followUp/customer',
        query
      })
    },
    handleDetail(item) {
      const { id } = item
      this.$router.push({
        path: '/customer/opty/category',
        query: { id }
      })
    },
    refreshOptyItem({ type, id }) {
      // type:操作类型：addcategory 添加品类， follow  跟进 ， allocation 分配设计师
      const index = this.list.findIndex(v => v.id === id)
      if (index === -1) return

      const data = new FormData()
      data.append('page', 1)
      data.append('rows', 1)
      data.append('sort', 'createTime')
      data.append('order', 'desc')
      data.append('filtersRaw', JSON.stringify([{
        id: 'id', property: 'id', operator: '=', value: id
      }]))
      data.append('paramsRaw', JSON.stringify({ queryDesignerList: '1' }))

      const headers = {
        'Permission-PerCode': this.isCommonCustomerPool ? 'common_customer_pool' : 'my_customer_pool',
        'Permission-App': 'top2-crm-app'
      }
      // TODO:是否权限待定
      optyDisPage(data, headers).then(res => {
        const records = res.data.records || []
        if (records?.length > 0) {
          this.$set(this.list, index, records[0])
        }
      })
    },
    getNoFollowDateCount(row) {
      const lastFollowupTime = row.lastFollowupTime || ''
      let count = 0
      if (lastFollowupTime) {
        const now = new Date().getTime()
        const start = new Date(lastFollowupTime).getTime()
        const d = now - start
        count = parseInt(d / 1000 / 60 / 60 / 24)
      }
      return count
    },
    getHtmlContent(content) {
      if (!content) return ''
      const html = content.replace(/{\r\n|{/g, '{<br/>').replace(/\r\n}|}/g, '<br/>}').replace(/\r\n/g, '<br/>')
      return html
    },
    getFollowupUser(list) {
      if (!list || list.length === 0) return '--'
      return list.map(v => v.userTrueName).join(',')
    }
  }
}

</script>
<style lang='less' scoped>
  .opty-record{
    padding: 16px;
    .c-list-scroll{
      min-height: calc(35vh);
    }
    .record-item{
      position: relative;
      padding: 16px;
      margin-bottom: 20px;
      background: #F8F8FA;
      border-radius: 16px;
      line-height: 20px;
      font-size: 14px;
      .fw{
        font-weight: bold;
      }
      .c-blak{
        color: #3C4458;
      }
      .item-title{
        margin-bottom: 30px;
        min-height: 20px;
        display: flex;
        align-content: space-between;
        justify-content: space-between;
        .tip{
          margin-left: 20px;
          padding:0 6px;
          height: 20px;
          color: #EE671A;
          background: rgba(238, 103, 26, 0.1);
          border-radius: 6px;
        }
      }
      .item-follow{
        color: #3C4458;
      }
      .item-content{
        margin: 16px 0;
        color: #B5B7C4;
      }
      .item-bottom{
        display: flex;
        align-items: center;
        justify-content: flex-end;
        .btn{
          display: inline-block;
          margin-left: 8px;
          padding: 0 12px;
          min-width:80px;
          height: 34px;
          line-height: 32px;
          border-radius: 10px;
          border: 1px solid #16BC83;
          box-sizing: border-box;
          color: #16BC83;
          text-align: center;
          font-size: 14px;
          font-weight: bold;
        }
      }
    }
  }
</style>
